package com.oj.core.util;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Bing on 2018/5/3.
 */

public class OJCoreC {

    public void compile(String command) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        //取得命令结果的输出流
        InputStream fis=process.getInputStream();
        //用一个读输出流类去读
        InputStreamReader isr=new InputStreamReader(fis);
        //用缓冲器读行
        BufferedReader br=new BufferedReader(isr);
        String line=null;
        //直到读完为止
        while((line=br.readLine())!=null)
        {
            System.out.println(line);
        }
        br.close();
        isr.close();
        fis.close();
    }
    public void run(String command) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);

        new Thread(new Runnable() {
            @Override
            public void run() {
                OutputStream os = null ;
                try {
                    Thread.sleep(2*1000);
                    os = process.getOutputStream();
                    BufferedReader proIn = new BufferedReader(new InputStreamReader(new FileInputStream(new File("D:\\idaworkspace\\JavaTest\\check\\input\\001.txt"))));
                    String in = null;
                    while((in=proIn.readLine())!=null){
                        System.out.println("输入："+in);
                        os.write((in+"\n").getBytes());//  \n  很重要
                        os.flush();
                    }
                    System.out.println("input end .....");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        //程序输出
        BufferedReader proOut = new BufferedReader(new InputStreamReader(process.getInputStream()));
        //获取真正的结果
        BufferedReader result = new BufferedReader(new InputStreamReader(new FileInputStream(new File("D:\\idaworkspace\\JavaTest\\check\\output\\001.txt"))));
        String outc = null;
        String resultc = null;
        boolean resultFlag = false;
        while ((outc = proOut.readLine())!=null){
            System.out.println("结果："+outc);
            resultc = result.readLine();
            if(resultc.equals(outc)){//自己加断点看结果  输出已经重置了 没办法输出到控制台
                resultFlag = true;
            }else{
                resultFlag = false;
                break;
            }
        }
        if(resultFlag){
            System.out.println("Accept!");
        }else{
            System.out.println("Error!");
        }
    }

    public static void main(String[] args){

        String code = "#include <stdio.h>\n" +
                "\n" +
                "int main(){\n" +
                "\tint a,b;\n" +
                "\t\n" +
                "\tfor(int i=0;i<2;i++){\n" +
                "\t\tscanf(\"%d %d\",&a,&b);\n" +
                "\t\tprintf(\"%d\\n\",a+b);\n" +
                "\t}\n" +
                "\treturn 0;\n" +
                "}\n";

        String fileName = "admin001"+ "_"
                + System.currentTimeMillis() + "Main";

        // 创建当天的代码提交文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(new Date());
        File dir = new File("admin001" + File.separator
                + today);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                System.out.println("创建文件夹失败，无法保存用户代码");
            }
        }
        System.out.println(dir.getAbsolutePath());

        FileOutputStream outputStream = null;
        String filePath =  fileName + ".c";
        try {
            outputStream = new FileOutputStream(filePath);
            outputStream.write(code.getBytes());

            System.out.println(System.getProperties().get("user.dir"));
            System.out.println("C:\\TDM-GCC-64\\bin\\gcc -o "+fileName+".exe "+fileName+".c");
            //编译
            new OJCoreC().compile("cmd /c C:\\TDM-GCC-64\\bin\\gcc -o "+fileName+".exe "+fileName+".c");

            Long freeMemory = Runtime.getRuntime().freeMemory();
            System.out.println("freeMemory :" + Runtime.getRuntime().freeMemory());
            //运行
            new OJCoreC().run(System.getProperties().get("user.dir")+File.separator+fileName+".exe");

            System.out.println("freeMemory :" + Runtime.getRuntime().freeMemory());

            System.out.println("useMemory :" + (freeMemory-Runtime.getRuntime().freeMemory()));


//            new OJCore().execCmd("cmd /c  D:/test.bat "+filePath+" "+dir.getAbsolutePath()+" "+fileName,dir,fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
